package com.sz.sgs.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

//写一个工具类； 专门用来处理Http中的get,post请求！
public class HttpClientUtils {


    //专门用来处理Http中的get请求！
    public static String  getMethod(String url){
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);   //相当于是在浏览器地址栏中输入了一个url地址后回车！
        try {
            HttpResponse response = client.execute(get);
            System.out.println(response.getStatusLine());   //200
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            get.releaseConnection();//释放get请求；
        }
        return result;
    }


    //写一个工具类； 专门用来处理Http中的post请求！
    public static String  postMethod(String url,String json){
        String result = "";
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);   //相当于是表单提交；
        try {
            StringEntity se = new StringEntity(json,"UTF-8");
            post.setHeader("Content-Type","application/json;charset=UTF-8");
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine());   //200
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();//释放get请求；
        }
        return result;
    }

    public static void main(String[] args) {

        //测试get请求；
        String result = getMethod("http://localhost:9999/citys/deleteCity/22");
        System.out.println(result);
    }
}
